<template>
  <div class="ai-assistant">
    <div class="chat-history">
      <div v-for="(message, index) in chatMessages" :key="index" class="message">
        <span :class="{ 'user-message': message.sender === 'user', 'assistant-message': message.sender === 'assistant' }">
          {{ message.text }}
        </span>
      </div>
      <!-- 显示加载状态 -->
      <div v-if="isLoading" class="loading">正在加载...</div>
    </div>
    <div class="input-container">
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入你的问题..." />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import callVolcengineApi from '@/api/volcengineApi';

// 初始化聊天消息数组
const chatMessages = ref<{ sender: 'user' | 'assistant'; text: string }[]>([]);
// 绑定用户输入框的值
const userInput = ref('');
// 加载状态
const isLoading = ref(false);

// 发送消息的函数
const sendMessage = async () => {
  if (userInput.value.trim() === '') return;

  // 添加用户消息到聊天历史
  chatMessages.value.push({ sender: 'user', text: userInput.value });
  // 清空输入框
  userInput.value = '';
  // 开始加载
  isLoading.value = true;

  try {
    const response = await callVolcengineApi(chatMessages.value[chatMessages.value.length - 1].text);
    console.log(response, 'response');
    
    if (response) {
      // 添加大模型的回复到聊天历史
      chatMessages.value.push({ sender: 'assistant', text: response.result });
    }
  } catch (error) {
    console.error('请求大模型时出错:', error);
    chatMessages.value.push({ sender: 'assistant', text: '抱歉，出现了一些问题，请稍后再试。' });
  } finally {
    // 结束加载
    isLoading.value = false;
  }
};
</script>

<style scoped>
.ai-assistant {
  display: flex;
  flex-direction: column;
  height: 500px;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
}

.chat-history {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.message {
  margin-bottom: 10px;
}

.user-message {
  background-color: #e0f7fa;
  padding: 8px;
  border-radius: 5px;
  align-self: flex-end;
  max-width: 70%;
}

.assistant-message {
  background-color: #f1f8e9;
  padding: 8px;
  border-radius: 5px;
  align-self: flex-start;
  max-width: 70%;
}

.loading {
  color: gray;
  font-style: italic;
  text-align: center;
  margin-top: 10px;
}

.input-container {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ccc;
}

.input-container input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.input-container button {
  padding: 8px 15px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.input-container button:hover {
  background-color: #1976d2;
}
</style>

